package com.ywj.chatroom.multiroom.server.handler;

import com.ywj.chatroom.multiroom.message.LoginRequestMessage;
import com.ywj.chatroom.multiroom.message.LoginResponseMessage;
import com.ywj.chatroom.multiroom.server.service.UserServiceFactory;
import com.ywj.chatroom.multiroom.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

//import java.nio.channels.Channel;
import io.netty.channel.Channel;
/**
 * 登录消息处理器
 * 1.获取用户名密码，进行检测   2.把channel和名字相对应起来存入map中   3.发通知
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage message = null;
        if(login){
            message = new LoginResponseMessage(true, "登录成功");
            SessionFactory.getSession().bind((Channel) ctx.channel(), username);
        }else{
            message = new LoginResponseMessage(false, "用户名或者密码不正确");
        }
        ctx.writeAndFlush(message);
    }
}
